﻿using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data.Entity;
using SimpleBlog.Infrastructure;
using SimpleBlog.Controllers;
using SimpleBlog.Helpers;
using SimpleBlog.Infrastructure.Database;

namespace SimpleBlog
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "SimpleBlog", // Route name
                "{controller}/{name}", // URL with parameters
                new { action = "Index" }, // Parameter defaults
                new { controller = @"Tag|Post" , name = @"[\s\S]+" }, //Parameter constraints
                new[] { "SimpleBlog.Controllers" }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Blog", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
                new[] { "SimpleBlog.Controllers" }
            );
        }

        protected void Application_Start()
        {
            Database.SetInitializer<SbContext>(new SbInitializer());
            using (var context = new SbContext())
            {
                context.Database.Initialize(force: true);
            }

            DependencyResolver.SetResolver(new SbResolver());
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_Error()
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            if (httpException == null)
            {
                httpException = new HttpException((int)HttpStatusCode.InternalServerError, "Internal Server Error", exception);
            }

            Server.LogException(httpException);
            Server.ClearError();

            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "Index";
            routeData.Values["exception"] = httpException;
            
            Response.Clear();
            Response.TrySkipIisCustomErrors = true; // Avoid IIS7 getting in the middle
            Response.StatusCode = httpException.GetHttpCode();

            IController errorController = DependencyResolver.Current.GetService<ErrorController>();
            HttpContextWrapper wrapper = new HttpContextWrapper(Context);
            RequestContext context = new RequestContext(wrapper, routeData);
            errorController.Execute(context);
            CompleteRequest();
        }
    }
}